<?php

namespace app\controller\weappapi;

use app\BaseController;
use app\middleware\AuthComment;
use app\model\{
	User as ModelUser
};

/**
 * @api 用户登陆类
 * @AuthComment loginModels ["User"]
 * @desc 常用的用户登陆示例
 */
class User extends BaseController
{
	// 中间件
	protected $middleware = [AuthComment::class];

	/**
	 * @api 小程序code登录
	 * @AuthComment loginModels []
	 */
	public function code2Token($code = '')
	{
		$app = app('use_wechat')->getMiniApp();

		$utils = $app->getUtils();
		try {
			$data = $utils->codeToSession($code);
		} catch (\Exception $e) {
			return failed($e->getMessage());
		}

		$user = ModelUser::where('openid', $data['openid'])->find();

		$isRegister = !$user;

		if ($isRegister) {
			// 新增用户
			$user = ModelUser::find(ModelUser::create([
				'openid' => $data['openid'],
				'unionid' => $data['unionid'] ?? '',
				'session_key' => $data['session_key'],
				'nickname' => '微信用户', // 默认昵称
				'avatar' => '', // 默认头像
			])['id']);
		} else {
			$user->save(['session_key' => $data['session_key']]);
		}

		// 更新登录信息
		$user->updateLoginInfo();

		// 触发用户注册事件
		if ($isRegister) event('UserRegister', $user);

		// 生成token
		$tokenApp = ModelUser::getTokenApp();
		$tokenApp->saveData($user['id'], $user); // 保存用户数据到Token中
		$tokenApp->clear($user['id']); // 清除旧的Token，有这一行就是单点登录
		$token = $tokenApp->create($user['id']);

		return success(['token' => $token]);
	}

	/**
	 * @api 获取用户信息
	 */
	public function getInfo()
	{
		$user = $this->request->AuthComment->getLoginModel('User');

		return success($user->append([]));
	}
}
